import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';

// 权限检查工具
const Auth = {
    isAuthenticated: false,
    login(callback) {
        this.isAuthenticated = true;
        setTimeout(callback, 100);
    },
    logout(callback) {
        this.isAuthenticated = false;
        setTimeout(callback, 100);
    },
    getToken() {
        return localStorage.getItem('token');
    },
    setToken(token) {
        localStorage.setItem('token', token);
    },
    removeToken() {
        localStorage.removeItem('token');
    },
    checkAuth() {
        const token = this.getToken();
        this.isAuthenticated = !!token;
        return this.isAuthenticated;
    }
};

// 路由守卫组件
export const PrivateRoute = ({ children }) => {
    const isAuth = Auth.checkAuth();
    
    if (!isAuth) {
        return <Navigate to="/login" replace />;
    }
    
    return children ? children : <Outlet />;
};

// 登录重定向组件
export const RedirectIfAuthenticated = ({ children }) => {
    const isAuth = Auth.checkAuth();
    
    if (isAuth) {
        return <Navigate to="/home" replace />;
    }
    
    return children;
};

export default Auth;